import os
import subprocess


def merge_videos(input_path, output_file, ffmpeg_path='ffmpeg'):

    file_name = os.listdir(input_path)
    video_path = []
    for file in file_name:
        video_path.append(os.path.join(input_path, file))

    list_file = 'temp_file_list.txt'
    with open(list_file, 'w', encoding='utf-8') as f:
        for file in video_path:
            f.write(f"file '{os.path.abspath(file)}'\n")

    command = [
        ffmpeg_path,
        '-f', 'concat',  # 指定拼接协议
        '-safe', '0',  # 允许非常规文件路径
        '-i', list_file,  # 输入文件列表
        '-c', 'copy',  # 直接复制流不重新编码[1](@ref)
        '-y',  # 覆盖已存在文件
        output_file
    ]

    try:
        subprocess.run(command, check=True, stderr=subprocess.PIPE)
        print(f"视频合并成功：{output_file}")
    except subprocess.CalledProcessError as e:
        print(f"合并失败，错误信息：{e.stderr.decode('utf-8')}")
    finally:
        if os.path.exists(list_file):
            os.remove(list_file)


def merge_vid_aud(video_path, audio_path, output_path):
    command = [
        'ffmpeg',
        '-y',  # 覆盖已存在文件
        '-i', video_path,
        '-i', audio_path,
        '-c:v', 'copy',  # 复制视频流不重新编码
        '-c:a', 'aac',  # 音频编码为AAC格式（兼容性更好）
        '-strict', 'experimental',  # 允许非标准参数
        '-shortest',  # 以最短输入流为输出时长（针对非严格等长文件）
        output_path
    ]
    try:
        subprocess.run(command, check=True, stderr=subprocess.PIPE)
        print("合并成功！输出文件:", output_path)
    except subprocess.CalledProcessError as e:
        print(f"合并失败: {e.stderr.decode('utf-8')}")